﻿<template>
  <div class="problem-set-detail" v-loading="loading">
    <div v-if="problemSet" class="detail-content">
      <!-- 标题卡片 -->
      <el-card class="title-card">
        <div class="title-content">
          <div class="title-left">
            <h2 class="set-title">{{ problemSet.name }}</h2>
            <div class="badge-group">
              <el-tag v-if="problemSet.userRole === 'CREATOR'" type="success" effect="plain">创建者</el-tag>
              <el-tag v-else-if="problemSet.userRole === 'MEMBER'" type="info" effect="plain">成员</el-tag>
            </div>
          </div>
          <div class="title-right" v-if="problemSet.description">
            <p class="set-description">{{ problemSet.description }}</p>
          </div>
        </div>
      </el-card>

      <!-- 信息表格卡片 -->
      <el-card class="info-card">
        <!-- 信息表格 -->
        <div class="info-table">
          <div class="info-row">
            <div class="info-cell">
              <div class="cell-label">创建者</div>
              <div class="cell-value">
                <span>{{ problemSet.creatorName }}</span>
              </div>
            </div>
            <div class="info-cell">
              <div class="cell-label">创建时间</div>
              <div class="cell-value">{{ formatDateTime(problemSet.createdAt) }}</div>
            </div>
            <div class="info-cell">
              <div class="cell-label">成员数</div>
              <div class="cell-value">
                <span class="cell-number">{{ problemSet.memberCount }}</span>
                人
              </div>
            </div>
          </div>

          <div class="info-row">
            <div class="info-cell">
              <div class="cell-label">题目数</div>
              <div class="cell-value">
                <span class="cell-number">{{ problemSet.problemCount }}</span>
                题
              </div>
            </div>
            <div class="info-cell">
              <div class="cell-label">状态</div>
              <div class="cell-value">
                <el-tag :type="getStatusType(problemSet.status)" effect="plain" size="small">
                  {{ getStatusText(problemSet.status) }}
                </el-tag>
              </div>
            </div>
            <div class="info-cell">
              <div class="cell-label">可见性</div>
              <div class="cell-value">
                <el-tag :type="problemSet.isPublic ? 'success' : 'warning'" effect="plain" size="small">
                  {{ problemSet.isPublic ? "公开" : "私有" }}
                </el-tag>
              </div>
            </div>
          </div>

          <div class="info-row info-row-full" v-if="problemSet.userRole === 'CREATOR'">
            <div class="info-cell info-cell-full">
              <div class="cell-label">邀请码</div>
              <div class="cell-value invite-code-section">
                <div class="invite-code-display">
                  <span class="invite-code-text">{{ problemSet.inviteCode }}</span>
                </div>
                <div class="invite-code-actions">
                  <el-button @click="handleCopyInviteCode" type="primary">复制</el-button>
                  <el-button @click="handleGenerateInviteCode" type="success">重新生成</el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 标签页内容 -->
      <ProblemSetTabs :problemSet="problemSet" @refresh="loadProblemSet" />
    </div>

    <!-- 错误状态 -->
    <div v-else-if="!loading" class="error-state">
      <el-empty description="题目集不存在或已被删除">
        <el-button type="primary" @click="$router.push('/problemSet')">返回列表</el-button>
      </el-empty>
    </div>
  </div>
</template>

<script setup>
/**
 * @component ProblemSetDetail
 * @description 题目集详情页面
 * 遵循项目现有的设计模式和风格
 */

import { computed, onMounted } from "vue"
import { useRoute, useRouter } from "vue-router"
import { useProblemSetsStore } from "@/stores/modules/problem-set"
import { ElMessageBox } from "element-plus"
import { handleError, handleSuccess } from "@/utils/core/error-handler"
import ProblemSetTabs from "./components/problemSetTabs.vue"

const route = useRoute()
const router = useRouter()
const problemSetsStore = useProblemSetsStore()

// 数据定义
const loading = computed(() => problemSetsStore.loading)
const problemSet = computed(() => problemSetsStore.currentProblemSet)

// 加载题目集详情
const loadProblemSet = async () => {
  const id = route.params.id
  try {
    await problemSetsStore.getProblemSetById(id)
  } catch (error) {
    handleError(error, {
      message: "加载题目集详情失败",
      context: "ProblemSetDetail"
    })
  }
}

// 复制邀请码
const handleCopyInviteCode = async () => {
  try {
    await navigator.clipboard.writeText(problemSet.value.inviteCode)
    handleSuccess("邀请码已复制到剪贴板")
  } catch (error) {
    handleError(error, {
      message: "复制失败，请手动复制",
      showMessage: true,
      logToConsole: false
    })
  }
}

// 重新生成邀请码
const handleGenerateInviteCode = async () => {
  try {
    const { value: days } = await ElMessageBox.prompt("请输入有效天数（0=永久，1-365=临时）", "重新生成邀请码", {
      confirmButtonText: "生成",
      cancelButtonText: "取消",
      inputPattern: /^(0|[1-9]\d{0,2})$/,
      inputErrorMessage: "请输入0-365的整数",
      inputValue: "0"
    })

    const daysNum = parseInt(days) || 0
    if (daysNum > 365) {
      handleError(new Error("有效期最多365天"), {
        message: "有效期最多365天",
        context: "GenerateInviteCode"
      })
      return
    }

    const result = await problemSetsStore.generateInviteCode(route.params.id, daysNum)
    if (result.code === 200) {
      // 根据是否永久显示不同消息
      if (result.isPermanent) {
        handleSuccess("永久邀请码已生成")
      } else {
        handleSuccess(`临时邀请码已生成（${result.days}天有效）`)
      }
      await loadProblemSet()
    }
  } catch (error) {
    if (error !== "cancel") {
      handleError(error, {
        message: "生成邀请码失败",
        context: "GenerateInviteCode"
      })
    }
  }
}

const getStatusType = status => {
  const types = {
    DRAFT: "info",
    ACTIVE: "success",
    ARCHIVED: "warning"
  }
  return types[status] || "info"
}

const getStatusText = status => {
  const texts = {
    DRAFT: "草稿",
    ACTIVE: "活跃",
    ARCHIVED: "已归档"
  }
  return texts[status] || status
}

const formatDateTime = date => {
  if (!date) return ""
  const d = new Date(date)
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")} ${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`
}

// 初始化
onMounted(() => {
  loadProblemSet()
})
</script>

<style lang="scss" scoped>
@use "@/styles/base/variables" as *;
@use "@/styles/base/mixins" as *;

.problem-set-detail {
  max-width: 1200px;
  margin: 0 auto;
  padding: 24px 20px;
  background: var(--color-bg-tertiary);
  min-height: 100vh;
  @include theme-transition;

  @include respond-below(md) {
    padding: 20px 16px;
  }

  .detail-content {
    // 标题卡片
    .title-card {
      background: white;
      border-radius: $border-radius-lg;
      box-shadow: var(--shadow-sm);
      border: 1px solid var(--color-border-secondary);
      margin-bottom: 16px;
      padding: 20px;
      @include theme-transition;

      @include respond-below(md) {
        padding: 16px;
      }

      .title-content {
        display: flex;
        justify-content: space-between;
        align-items: center;
        gap: 24px;

        @include respond-below(md) {
          flex-direction: column;
          align-items: flex-start;
        }

        .title-left {
          flex-shrink: 0;
          display: flex;
          align-items: center;
          gap: 12px;

          .set-title {
            font-size: 24px;
            font-weight: 700;
            color: var(--color-text-primary);
            margin: 0;
            line-height: 1.3;
            white-space: nowrap;
          }

          .badge-group {
            display: flex;
            gap: 6px;
            flex-shrink: 0;

            :deep(.el-tag) {
              font-size: 12px;
              padding: 4px 10px;
              border-radius: $border-radius-base;
              font-weight: 600;
            }
          }
        }

        .title-right {
          flex: 1;
          min-width: 0;
          display: flex;
          align-items: center;

          .set-description {
            font-size: 14px;
            color: var(--color-text-secondary);
            margin: 0;
            line-height: 1.6;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
          }
        }
      }
    }

    // 信息表格卡片
    .info-card {
      background: var(--color-bg-primary);
      border-radius: $border-radius-lg;
      box-shadow: var(--shadow-sm);
      border: 1px solid var(--color-border-secondary);
      margin-bottom: 16px;
      overflow: hidden;
      @include theme-transition;

      .info-table {
        .info-row {
          display: grid;
          grid-template-columns: repeat(3, 1fr);
          border-bottom: 1px solid var(--color-border-tertiary);

          @include respond-below(md) {
            grid-template-columns: 1fr;
          }

          &:last-child {
            border-bottom: none;
          }

          &.info-row-full {
            grid-template-columns: 1fr;
          }
        }

        .info-cell {
          padding: 12px 18px;
          border-right: 1px solid var(--color-border-tertiary);

          @include respond-below(md) {
            border-right: none;
            border-bottom: 1px solid var(--color-border-tertiary);

            &:last-child {
              border-bottom: none;
            }
          }

          &:last-child {
            border-right: none;
          }

          .cell-label {
            font-size: 12px;
            font-weight: 600;
            color: var(--color-text-tertiary);
            margin-bottom: 6px;
          }

          .cell-value {
            font-size: 15px;
            color: var(--color-text-primary);
            font-weight: 500;
            display: flex;
            align-items: center;
            gap: 8px;

            .cell-number {
              font-size: 16px;
              font-weight: 700;
              color: var(--color-primary);
            }

            &.description-content {
              line-height: 1.7;
              white-space: pre-wrap;
              color: var(--color-text-secondary);
              padding: 12px 14px;
              background: var(--color-bg-quaternary);
              border-radius: $border-radius-base;
              border-left: 3px solid var(--color-primary);
              display: block;
            }

            &.invite-code-section {
              display: flex;
              align-items: center;
              gap: 10px;

              @include respond-below(md) {
                flex-direction: column;
                align-items: stretch;
              }

              .invite-code-display {
                flex: 1;
                padding: 10px 18px;
                background: linear-gradient(135deg, rgba($color-primary, 0.08) 0%, rgba($color-primary, 0.03) 100%);
                border: 2px solid var(--color-primary-light-7);
                border-radius: $border-radius-base;
                text-align: center;
                transition: all $transition-fast;

                &:hover {
                  border-color: var(--color-primary);
                  background: linear-gradient(135deg, rgba($color-primary, 0.12) 0%, rgba($color-primary, 0.05) 100%);
                }

                .invite-code-text {
                  font-family: $font-family-code;
                  font-size: 18px;
                  font-weight: 700;
                  color: var(--color-primary);
                  letter-spacing: 2px;
                  user-select: all;
                }
              }

              .invite-code-actions {
                display: flex;
                gap: 8px;

                @include respond-below(md) {
                  width: 100%;

                  .el-button {
                    flex: 1;
                  }
                }
              }
            }
          }
        }
      }
    }
  }

  .error-state {
    background: var(--color-bg-primary);
    border-radius: $border-radius-lg;
    padding: 48px;
    text-align: center;
    box-shadow: var(--shadow-sm);
    border: 1px solid var(--color-border-secondary);
    @include theme-transition;
  }
}
</style>
